<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use App\Models\AdminModule;
use App\Models\AdminNav;
use App\Models\AdminPower;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class Auth extends Base
{
    /**
     * 前台用户注册
     */
    public function registerUser(Request $request){
        $data = $request->post();
        $rules = [
            'email'=>'required|unique:users|email',
            'password'=>'required|alpha_num|confirmed',
            'password_confirmation'=>'required|same:password',
            'contact'=>'required|string',
            'username'=>'required|string',
            'birthday'=>'required|date_format:"Y-m-d"'
        ];
        $messages = [
            'email.required'=> '请填写邮箱',
            'email.email'=> '请填写正确的邮箱地址',
            'email.unique'=> '该邮箱已注册',
            'password.required'=> '请填写密码',
            'password.alpha_num'=> '密码必须由数字和字母组成',
            'password.confirmed'=> '请填写确认密码',
            'password_confirmation.required'=> '请填写确认密码',
            'password_confirmation.same'=> '两次密码不一致',
            'contact.required'=> '请填写联系方式',
            'username.required'=> '请填写姓名',
            'birthday.required'=> '请填写生日',
            'birthday.date_format'=> '请选择正确的日期'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        unset($data['password_confirmation']);
        $data['password'] = Hash::make($data['password']);
        $model  =  new UserModel() ;
        $result = $model-> userAdd($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'registerUser');
            return response()->json([
                'code'=>20002,
                'message'=>'用户添加失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'用户添加成功'
            ]);
        }
    }

    // 管理员登录接口
    public function userLogin(Request $request){
        $data = $request->post();
        $rules = [
            'username'=>'required|string',
            'password'=>'required|alpha_num'
        ];
        $messages = [
            'username.required'=> '请填写账号',
            'password.required'=> '请填写密码',
            'password.alpha_num'=> '密码必须由数字和字母组成'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        try {
            $admin = DB::table('admins')->leftJoin('admin_roles','admin_roles.id','=','admins.roleid')
                ->where([
                    ['username','=',$data['username']],['admins.deleted_at','=',null]
                ])
                ->select('admins.id','username','password','roleid','rolename')->first();
            if($admin){
                if(!Hash::check($data['password'],$admin->password)){ //密码不正确时
                    return response()->json([
                        'code'=>20022,
                        'message'=>'密码不正确'
                    ]);
                }else{
                    //设置登录token
                    $token = $this->setToken($admin);
                    DB::table('admins')->where('username',$data['username'])->update(['token'=>$token]);
                    return response()->json([
                        'code'=>0,
                        'data'=>$token
                    ]);
                }
            }else{
                return response()->json([
                    'code'=>20021,
                    'message'=>'账户不存在'
                ]);
            }
        }catch (\Exception $e){
            $this->logErr($e->getCode(),$e->getMessage(),'adminLogin');
            return response()->json([
                'code'=>20023,
                'message'=>'登录失败,请重试'
            ]);
        }

    }

    //管理员退出
    public function userLogout(){
        return response()->json([
            'code'=>0,
            'message'=>'退出成功'
        ]);
    }

    //获取管理员权限
    public function getAdminInfos(Request $request){
        try {
            $admin = DB::table('admins')->leftJoin('admin_roles','admin_roles.id','=','admins.roleid')
                    ->where([
                        ['token','=',$request->logintoken],['admins.deleted_at','=',null]
                    ])
                    ->select('admins.id','username','password','roleid','rolename')->first();
            if($admin){
                //获取管理员权限
                $model = new Admin();
                $return = $model->getPowers($admin);
                if($return['code']){
                    return response()->json($return);
                }
                //重置登录令牌
                $newtoken = $this->setToken($admin);
                DB::table('admins')->where('id',$admin->id)->update(['token'=>$newtoken]);
                $return['data']['login'] = $newtoken;
                $return['data']['info'] = $admin;
                return response()->json($return);
            }else{
                return response()->json([
                    'code'=>20221,
                    'message'=>'无法识别管理员或无管理权限'
                ]);
            }
        }catch (\Exception $e){
            $this->logErr($e->getCode(),$e->getMessage(),'adminLogin');
            return response()->json([
                'code'=>20023,
                'message'=>'请求失败,请重试'
            ]);
        }
    }

    /**
     *模块添加接口
     */
    public function moduleCreate(Request $request){
        $data = $request->post();
        $rules = [
            'modname'=>'required|string',
            'modspace'=>'required|alpha'
        ];
        $messages = [
            'modname.required'=> '请填写模块中文名',
            'modspace.required'=> '请填写模块控制器名称',
            'modspace.alpha'=> '控制器名称必须由字母组成'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminModule();
        $result = $model->modAdd($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'createAdminModule');
            return response()->json([
                'code'=>20031,
                'message'=>'模块添加失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'模块添加成功'
            ]);
        }
    }

    /**
     * @param Request $request
     * 模块编辑
     */
    public function moduleUpdate(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'modname'=>'required|string',
            'modspace'=>'required|alpha'
        ];
        $messages = [
            'modname.id'=> '请选择模块',
            'modname.required'=> '请填写模块中文名',
            'modspace.required'=> '请填写模块控制器名称',
            'modspace.alpha'=> '控制器名称必须由字母组成'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminModule();
        $result = $model->modUpdate($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'editAdminModule');
            return response()->json([
                'code'=>20031,
                'message'=>'模块编辑失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'模块编辑成功'
            ]);
        }
    }

    /**
     *模块添加接口
     */
    public function navCreate(Request $request){
        $data = $request->post();
        $rules = [
            'navname'=>'required|string',
            'navaction'=>'required|string',
            'moid'=>'required|integer'
        ];
        $messages = [
            'navname.required'=> '请填写菜单名称',
            'moid.required'=> '请选择模块',
            'navaction.required'=> '请填写菜单操作名称',
            'moid.integer'=> '模块参数不正确'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminNav();
        $result = $model->navAdd($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'createAdminModule');
            return response()->json([
                'code'=>20031,
                'message'=>'菜单添加失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'菜单添加成功'
            ]);
        }
    }

    /**
     * 权限添加接口
     * @param Request $request
     *
     */
    public function powerCreate(Request $request){
        $data = $request->post();
        $rules = [
            'powername'=>'required|string',
            'navid'=>'required|integer',
            'powertype'=>'required|integer',
            'path'=>'required|string'
        ];
        $messages = [
            'powername.required'=> '请填写权限名称',
            'navid.required'=> '请选择菜单',
            'powertype.required'=> '请选择权限类型',
            'path.required'=> '请填写页面路径'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminPower();
        unset($data['navname']);
        unset($data['navaction']);
        $result = $model->powerAdd($data);

        if($result['code']){
            $this->logErr($result['code'],$result['message'],'powerCreate');
            return response()->json([
                'code'=>20041,
                'message'=>'权限添加失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'权限添加成功'
            ]);
        }
    }

    //获取模块列表
    public function moduleList(Request $request){
        $data = $request->all();
        $limit = $data['limit'];
        $page = $data['page'];
        $where = [];
        $data = (new AdminModule())->getModPageList(['limit'=>$limit,'page'=>$page],$where);
        return response()->json($data);
    }

    //获取菜单列表
    public function navList(Request $request){
        $data = $request->all();
        $limit = $data['limit'];
        $page = $data['page'];
        $where = [];
        $data = (new AdminNav())->getNavPageList(['limit'=>$limit,'page'=>$page],$where);
        return response()->json($data);
    }

    /**
     * @param Request $request
     * 菜单编辑
     */
    public function navUpdate(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'moid'=>'required|integer',
            'navname'=>'required|string',
            'navaction'=>'required|alpha'
        ];
        $messages = [
            'id.required'=> '请选择菜单',
            'moid.required'=> '请选择模块',
            'navname.required'=> '请填写菜单中文名',
            'navaction.required'=> '请填写菜单操作名称',
            'navaction.alpha'=> '菜单操作名称必须由字母组成'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminNav();
        $result = $model->navUpdate($data);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'editAdminNav');
            return response()->json([
                'code'=>20031,
                'message'=>'菜单编辑失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'菜单编辑成功'
            ]);
        }
    }

    //获取权限列表
    public function powerList(Request $request){
        $data = $request->all();
        $limit = $data['limit'];
        $page = $data['page'];
        $searchCont = (isset($data['searchcontent']) && $data['searchcontent'])?$data['searchcontent']:'';
        $startDate = (isset($data['startDate']) && $data['startDate'])?$data['startDate']:'';
        $endDate = (isset($data['endDate']) && $data['endDate'])?$data['endDate']:'';
        $where = [];
        if($searchCont){
            $where[] = ['powername','like','%'.$searchCont.'%'];
        }
        $whereDates = [];
        if($endDate){
            $entime = strtotime($endDate) + 24*3600;
            $endDate = date('Y-m-d',$entime);
        }
        if($startDate && $endDate){
            $whereDates = [$startDate,$endDate];
        }
        $data = (new AdminPower())->getPageList(['limit'=>$limit,'page'=>$page],$where,$whereDates);
        return response()->json($data);
    }

    /**
     * @param Request $request
     * 权限编辑
     */
    public function powerUpdate(Request $request){
        $data = $request->post();
        $rules = [
            'id'=>'required|integer',
            'powername'=>'required|string',
            'navid'=>'required|integer',
            'powertype'=>'required|integer',
            'path'=>'required|string'
        ];
        $messages = [
            'id.required'=> '请选择权限',
            'powername.required'=> '请填写权限名称',
            'navid.required'=> '请选择菜单',
            'powertype.required'=> '请选择权限类型',
            'path.required'=> '请填写页面路径'
        ];
        $check = $this->checkParams($data,$rules,$messages);
        if($check['code']){
            return response()->json($check);
        }
        $model =  new  AdminPower();
        $result = $model->doUpdate($data);
//        return response()->json($result);
        if($result['code']){
            $this->logErr($result['code'],$result['message'],'editAdminPower');
            return response()->json([
                'code'=>20031,
                'message'=>'权限编辑失败,请重试'
            ]);
        }else{
            return response()->json([
                'code'=>0,
                'message'=>'权限编辑成功'
            ]);
        }
    }

}
